<?php
/**
 * kol视频上传
 * User: bgl
 * Date: 2023/3/14
 * Time: 0:22
 */

namespace App\Admin\Controllers\KolManage;


use App\Importer\Basics\BImporter;
use App\Models\KolManage\KolVideo;
use Encore\Admin\Controllers\AdminController;
use App\Util\RExcel;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;
use Symfony\Component\HttpFoundation\File\UploadedFile;

class KolVideoUploadController extends AdminController{

    protected $title = 'Kol-video上传';

    protected function grid()
    {
        $type = request('type');
        return view("kol-manage.kol-video.index",compact('type'));
    }

    public function upload(Request $request){
        $file = $request->file('source_file');
        if ($file->isValid()) {
            $action = $request->get('action');
            $re = $this->{'_import'.$action}($file);
            if(is_array($re)) {
                if($re['flag']){
                    admin_toastr('文件：'.$re['data'].' 上传成功！');
                }else{
                    admin_toastr($re['data'],'error');
                }
            }else{
                return $re;
            }
        }else{
            admin_toastr('无效文件！','error');
        }
        return back()->withInput();
    }

    private function _importCreate(UploadedFile $file){

        try{
            $data = Excel::toArray(new BImporter(), $file);
            $data = $data[0];

            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $userId = Admin::user()->id;

            foreach($data as $row){
                $count++;
                $orderNo        = $row[0] ? trim($row[0]) : '';
                $kolId          = $row[1] ? trim($row[1]) : '';
                $linkType       = $row[2] ? trim($row[2]) : '';
                $linkUrl        = $row[3] ? trim($row[3]) : '';
                $linkOnlineTime = $row[4] ? trim($row[4]) : '';
                $likeNum        = $row[5] ? trim($row[5]) : '';
                $viewNum        = $row[6] ? trim($row[6]) : '';
                $commentNum     = $row[7] ? trim($row[7]) : '';
                $convertNum     = $row[8] ? trim($row[8]) : '';
                $advertCost     = $row[9] ? trim($row[9]) : '';
                $exchangeRate   = $row[10] ? trim($row[10]) : '';
                $remark         = $row[13] ? trim($row[13]) : '';
                $_status        = $row[14] ? trim($row[14]) : '停用';

                if(!$orderNo || !$kolId){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                if(!in_array($linkType, KolVideo::$_link_type)){
                    $errors[$count] = '['.$linkType.'],不存在，请选择链接类型: '.implode('、', KolVideo::$_link_type);
                    continue;
                }

                $status = array_search($_status, KolVideo::$_status);
                if(!$status){
                    $errors[$count] = '['.$_status.'],不存在该状态，请选择'.implode('、',KolVideo::$_status);
                    continue;
                }

                $reCount = KolVideo::query()
                    ->where('kol_id', $kolId)
                    ->where('order_no', $orderNo)
                    ->count();
                if($reCount > 0){
                    $errors[$count] = '['.$orderNo.'],系统已存在该订单号，需要更新请前往更新';
                    continue;
                }

                DB::beginTransaction();
                $obj = KolVideo::query()->create([
                    'order_no' => $orderNo,
                    'kol_id' => $kolId,
                    'link_type' => $linkType,
                    'link_url' => $linkUrl,
                    'link_online_time' => $linkOnlineTime,
                    'like_num' => $likeNum,
                    'view_num' => $viewNum,
                    'comment_num' => $commentNum,
                    'convert_num' => $convertNum,
                    'advert_cost' => $advertCost,
                    'exchange_rate' => $exchangeRate,
                    'remark' => $remark,
                    'status' => $status,
                    'admin_id' => $userId,
                ]);
                if($obj){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true, 'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }
        }catch(\Exception $e){
            report($e);
            return ['flag' => false, 'data' => '系统异常！'];
        }
    }

    private function _importRakutenUpdate(UploadedFile $file){
        try{
            $data = Excel::toArray(new bImporter(),$file);
            $data = $data[0];
            if(!$data)return ['flag' => false,'data' => '请上传包含有数据的文件！'];
            $errors = [];
            $count = 1;
            $userId = Admin::user()->id;

            foreach($data as $row){
                $count++;
                $orderNo        = $row[0] ? trim($row[0]) : '';
                $kolId          = $row[1] ? trim($row[1]) : '';
                $linkType       = $row[2] ? trim($row[2]) : '';
                $linkUrl        = $row[3] ? trim($row[3]) : '';
                $linkOnlineTime = $row[4] ? trim($row[4]) : '';
                $likeNum        = $row[5] ? trim($row[5]) : '';
                $viewNum        = $row[6] ? trim($row[6]) : '';
                $commentNum     = $row[7] ? trim($row[7]) : '';
                $convertNum     = $row[8] ? trim($row[8]) : '';
                $advertCost     = $row[9] ? trim($row[9]) : '';
                $exchangeRate   = $row[10] ? trim($row[10]) : '';
                $remark         = $row[13] ? trim($row[13]) : '';
                $status        = $row[14] ? trim($row[14]) : '停用';

                if(!$orderNo || !$kolId){
                    $errors[$count] = '必填项为空';
                    continue;
                }

                if(!in_array($linkType, KolVideo::$_link_type)){
                    $errors[$count] = '['.$linkType.'],不存在，请选择链接类型: '.implode('、', KolVideo::$_link_type);
                    continue;
                }

                DB::beginTransaction();
                $obj = KolVideo::query()
                    ->where('kol_id', $kolId)
                    ->where('order_no', $orderNo)
                    ->first();
                if(!$obj){
                    $errors[$count] = '['.$orderNo.'],系统已存在该订单号，需要新增请前往新增';
                    DB::rollBack();
                    continue;
                }

                if(!$status){
                    if(!in_array($status,KolVideo::$_status)){
                        $errors[$count] = $status.'不存在，请选择'.implode('、',KolVideo::$_status);
                        continue;
                    }
                    $obj->status = array_search($status,KolVideo::$_status);
                }

                $obj->order_no = $orderNo;
                $obj->kol_id = $kolId;
                $obj->link_type = $linkType;
                $obj->link_url = $linkUrl;
                $obj->link_online_time = $linkOnlineTime;
                $obj->like_num = $likeNum;
                $obj->view_num = $viewNum;
                $obj->comment_num = $commentNum;
                $obj->convert_num = $convertNum;
                $obj->advert_cost = $advertCost;
                $obj->exchange_rate = $exchangeRate;
                $obj->remark = $remark;
                $obj->admin_id = $userId;

                if($obj->save()){
                    DB::commit();
                }else{
                    DB::rollBack();
                }
            }
            if(empty($errors)){
                return ['flag' => true,'data' => $file->getClientOriginalName()];
            }else{
                return RExcel::importResult($errors);
            }

        }catch(\Exception $e){
            report($e);
            return ['flag' => false,'data' => '系统异常！'];
        }
    }

    public function template(Request $request){
        $temp = $request->get('temp');
        $suffix = $request->get('suffix','xlsx');
        return Storage::disk('admin')->download("template/{$temp}-template.{$suffix}");
    }

}
